package tmt.usercenter.web.configure.sm;

import com.tmt.sm.ISmSender;
import com.tmt.sm.impl.DefaultSmSenderProxy;
import com.tmt.sm.impl.LkSmSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import tmt.usercenter.web.domain.enums.SystemParamCode;
import tmt.usercenter.web.service.SystemParamService;

/**
 * 短信服务配置
 * Created by ThreeManTeam on 2017/12/8.
 */
@Configuration
@ConditionalOnProperty(name={"sm-sender.enabled"}, havingValue = "true", matchIfMissing = false)
@EnableConfigurationProperties(LkSmSenderProperties.class)
public class SmServiceConfig {

    @Autowired
    private LkSmSenderProperties lkSmSenderProperties;

    @Autowired
    private SystemParamService systemParamService;

    private final Logger logger = LoggerFactory.getLogger(SmServiceConfig.class);

    @Bean
    public ISmSender smSendService() {
        DefaultSmSenderProxy smSenderProxy = new DefaultSmSenderProxy();
        Boolean enable = systemParamService.getSystemParamValue(SystemParamCode.SM_ENABLE_LK, Boolean.class);
        if (enable == null)
            enable = lkSmSenderProperties.isEnabled();

        if (enable){
            String account = systemParamService.getSystemParamValue(SystemParamCode.SM_ACCOUNT_LK, String.class);
            if (StringUtils.isEmpty(account))
                account = lkSmSenderProperties.getCorpId();

            String password = systemParamService.getSystemParamValue(SystemParamCode.SM_PASSWORD_LK, String.class);
            if (StringUtils.isEmpty(password))
                password = lkSmSenderProperties.getPassword();

            String url = systemParamService.getSystemParamValue(SystemParamCode.SM_URL_LK, String.class);
            if (StringUtils.isEmpty(url))
                url = lkSmSenderProperties.getSendUrl();

            LkSmSender smSender = new LkSmSender(account, password, url);
            smSenderProxy.addSender(smSender);
            logger.debug("----------加载了凌凯科技短信发送模块-----------");
        }
        return smSenderProxy;
    }

}
